package com.knoya.chejian.pda.util;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.knoya.chejian.pda.contacts.Contacts;
import com.knoya.chejian.pda.minterface.OnUserDataInterface;

import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpUtil {
    /**
     * 登陆
     *
     * @param name     账号
     * @param password 密码
     */
    public static void setLogin(Context context, String name, String password, String child_name, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.LOGIN);
        Log.e("TAAAG", params.toString());
        if(params==null) {
            Log.e("TAAAG", "bbbbbbbbbbbb");
        }
//        addssl(params, context);
        params.addBodyParameter("username", name, Contacts.BOUNDARY);
        params.addBodyParameter("password", password, Contacts.BOUNDARY);
        if (child_name != "") {
            params.addBodyParameter("child_name", child_name, Contacts.BOUNDARY);
        }
        params.addHeader("ACCEPT", "application/json");
        params.setConnectTimeout(6000);
        x.http().post(params, Call(context,onUserDataInterface));
    }

    /** 获取最新版本号数据*/
    public static void getUpdateInfo(Context context,final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.UPDATEINFO);
        x.http().get(params, Call(context,onUserDataInterface));
    }

    /** 下载apk*/
    public static void showUpdateInfo(Context context, String url, final String path, final ProgressBar pb, final TextView tv, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(url);
        params.setSaveFilePath(path);
        x.http().get(params, Callfile(context,onUserDataInterface, pb, tv));
    }


    /**
     * 下载文件的返回
     *
     * @param onUserDataInterface 回调监听
     * @param pb                  进度条
     * @param tv                  百分比
     * @return
     */
    public static Callback.ProgressCallback<File> Callfile(final Context context, final OnUserDataInterface onUserDataInterface, final ProgressBar pb, final TextView tv) {
        Callback.ProgressCallback<File> callfiles = new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long l, long l1, boolean b) {
                int schedule = (int) ((l1 * 100) / l);
                pb.setProgress(schedule);
                tv.setText(schedule + "%");
            }

            @Override
            public void onSuccess(File file) {
                Myutil.MyTost("下载成功" + file.toString());
                onUserDataInterface.onUserData(file.toString());
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                Myutil.onerror(throwable.toString(), (Activity) context);
                Myutil.MyTost("下载失败");
                Myutil.Mylog("TAAAG",throwable.toString());
                onUserDataInterface.onNot(throwable.toString());
            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        };
        return callfiles;
    }


    /**获取token*/
    public static void getToken(Context context, final OnUserDataInterface onuserdatainterface) {
        RequestParams params = new RequestParams(Contacts.TOKEN);
        getparams(context, params);
        params.addBodyParameter("page", "1111",Contacts.BOUNDARY);
        params.addBodyParameter("pagesize", "1111",Contacts.BOUNDARY);
        params.addHeader("Content-Type", "multipart/form-data");
        x.http().post(params, Call(context,onuserdatainterface));
    }

    private static SSLContext sslContext;
    /**
     * 为params添加cookie和ssl证书
     * @param context
     * @param params
     */
    public static void getparams(Context context, RequestParams params) {

        addcookie(params);
        params.setConnectTimeout(20000);
    }

    /**
     * 为params添加token
     */
    public static void addtoken(RequestParams params){
        Log.d("TAAG","token="+Sputil.sp("pda").getString("token", ""));
        params.addHeader("X-CSRF-TOKEN", Sputil.sp("pda").getString("token", ""));
    }


    /**
     * 获取数据的返回
     * @param onUserDataInterface
     * @return
     */
    public static Callback.CommonCallback<String> Call(final Context context, final OnUserDataInterface onUserDataInterface) {

        return new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                onUserDataInterface.onUserData(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("TAAG","ex="+ex.toString());
                if(ex.toString().trim().contains("a.a")){
                    Log.d("TAAG","ex=xxxxxxxxxxxxxxxxxxxxxx"+ex.toString());
                    onUserDataInterface.onNot(ex.toString());
                    return;
                }
                boolean isonerror = false;
                if (!isOnCallback) {
                    isonerror=Myutil.onerror(ex.toString(),(Activity) context);
                    onUserDataInterface.onNot(ex.toString());
                    if(isonerror){
                        return;
                    }
                }
                String[] ss = ex.toString().split("result:");
                if(ss.length>1) {
                    String edata = "";
                    try {
                        JSONArray js = new JSONArray(ss[1]);
                        if (js.length() != 0) {
                            edata = js.getString(0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if(!edata.trim().equals("")){
                        Myutil.httperrordiaog(context,Myutil.decodeUnicode(edata));
//                        Myutil.MyTost(Myutil.decodeUnicode(edata));
                    }else{
                        Myutil.MyTost(Myutil.decodeUnicode(ss[1]));
                    }
                }else{
                    Myutil.MyTost(Myutil.decodeUnicode(ex.toString()));
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        };
    }


    /**
     * 为网络访问添加cookie参数
     *
     * @param params          RequestParams对象
     */
    public static void addcookie(RequestParams params) {
        Log.d("TAAG","COOKIE="+Sputil.sp("pda").getString("cookie", ""));
        params.addHeader("COOKIE", Sputil.sp("pda").getString("cookie", ""));
    }
}
